<template>
  <div style="background-color: #f6f6f6">
    <el-row>
      <el-col :span="20" :offset="2">
        <div class="form" style="padding-left: 20px;">
          <el-form :inline="true" :model="search" class="dw-form-inline" size="medium" >
            <el-form-item label="用户名">
              <el-input v-model="search.key" placeholder="请输入要查询的用户名" clearable ></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px;">
              <el-button type="primary" icon="el-icon-search" @click="queryUser(search.key)">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="table">
          <div class="table-title">
            <el-row :span="24" type="flex" justify="space-between" align="middle">
              <el-col :span="4"><h3>用户管理</h3></el-col>
              <el-col :span="20" style="text-align: right;">
                <el-button type="primary" size="medium" @click="handleAdd()">创建用户</el-button>
              </el-col>
            </el-row>
          </div>
          <el-table :data="tableData.slice((currentPage-1)*pageSize,currentPage*pageSize)" stripe style="width: 100%" border>
            <el-table-column type="selection" width="55"></el-table-column>
            <el-table-column label="序号" width="50" type="index" sortable align="center"></el-table-column>
            <el-table-column label="用户名" width="170" prop="username" align="center"></el-table-column>
            <el-table-column label="用户电话" width="240" prop="telnumber" align="center"></el-table-column>
            <el-table-column label="用户状态" prop="status" width="120" align="center">
              <template v-slot="scope">
                <el-tag :type="getTagType(scope.row.status)">
                  <!-- 插值表达式支持函数执行 并且渲染的是函数的return值 -->
                  {{ formatStatus(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="租户名" prop="tenement" align="center" v-if="false"></el-table-column>
            <el-table-column label="用户可发布问卷上限" width="190" prop="maxpaper" align="center"></el-table-column>
            <el-table-column label="用户已发布问卷数量" width="190" prop="curpaper" align="center"></el-table-column>
            <el-table-column label="密保问题" prop="securityQuestionContext" align="center" v-if="false"></el-table-column>
            <el-table-column label="密保回答" prop="securityQuestionAnswer" align="center" v-if="false"></el-table-column>
            <el-table-column label="操作" width="224" align="center">
              <template v-slot="scope">
                <el-button size="primary" icon="el-icon-edit" circle @click="handleEdit(scope.row)"></el-button>
                <el-button size="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)" ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              :page-size="pageSize"
              :current-page="currentPage"
              :total="total"
              :page-sizes="[5,10,20,50]"
              background
              layout="sizes,prev, pager, next"
              @current-change="handleCurrentChange"
              @size-change="handleSizeChange"
            >
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>

    <div>
      <el-dialog :title="dialogTitle" :visible="dialogFormVisible" append-to-body width="40%" :close-on-click-modal="false" @close="handleClose()">
        <el-form ref="userForm" :model="userForm" :rules="userFormRules" status-icon label-position="top">
          <el-form-item :label-width="formLabelWidth" label="用户名" prop="username" style="margin-top: 0px;">
            <el-input v-model="userForm.username" autocomplete="off" placeholder="请输入用户名" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密码" prop="password" class="dw-dialog-form-item" v-if="this.dialogTitle=='创建用户'">
            <el-input v-model="userForm.password" autocomplete="off" placeholder="请输入密码" show-password ></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="确认密码" prop="checkPassword" class="dw-dialog-form-item" v-if="this.dialogTitle=='创建用户'">
            <el-input v-model="userForm.checkPassword" autocomplete="off" placeholder="请再次输入密码" show-password ></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="手机号" prop="telnumber" class="dw-dialog-form-item" >
            <el-input v-model="userForm.telnumber" autocomplete="off" placeholder="请输入手机号" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="账号状态" prop="status" class="dw-dialog-form-item" v-if="this.dialogTitle=='修改用户信息'">
            <el-radio-group v-model="userForm.status">
              <el-radio :label="0">正常</el-radio>
              <el-radio :label="1">冻结</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="用户可发布问卷上限" prop="maxpaper" class="dw-dialog-form-item" >
            <el-input v-model.number="userForm.maxpaper" autocomplete="off" placeholder="请输入用户可发布问卷上限" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密保问题" prop="securityQuestionContext" class="dw-dialog-form-item" >
            <el-input v-model="userForm.securityQuestionContext" autocomplete="off" placeholder="请输入密保问题" show-word-limit></el-input>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth" label="密保回答" prop="securityQuestionAnswer" class="dw-dialog-form-item" >
            <el-input v-model="userForm.securityQuestionAnswer" autocomplete="off" placeholder="请输入密保回答" show-word-limit></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="handleClose()">取 消</el-button>
          <el-button type="primary" @click="handleConfirm()">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {createUser, modifyUserInfo, queryUserList, queryUserByKey, removeUserByName} from '../../api/tenant.js'

export default {
  name: "tenantUsermanage",
  data (){
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        if (this.userForm.checkPassword !== '') {
          this.$refs['userForm'].validateField('checkPassword');
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.userForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      change: false,
      search: {
        key: null
      },
      tableData: [],
      pageSize: 5,
      currentPage: 1,
      total: 0,
      formInline: {
        loginName: null,
        status: null
      },
      dialogTitle: '创建用户',
      dialogFormVisible: false,
      loginerInfo:{},
      userForm: {
        id: '',
        username: '',
        password:'',
        checkPassword:'',
        telnumber: '',
        tenement:'',
        status:'',
        maxpaper: '',
        curpaper: 0,
        securityQuestionContext: '',
        securityQuestionAnswer: ''
      },
      userFormRules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
          {min: 1, max: 18, message: '长度在 1 到 18 个字符', trigger: 'blur'},
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        checkPassword: [
          { required: true, message: '请确认密码', trigger: 'blur' },
          { min: 6, max: 16, message: '长度在 6 到 16 个字符', trigger: 'blur' },
          { validator: validatePass2, trigger: 'blur', required: true }
        ],
        telnumber: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { pattern:/^1(3\d|4[5-9]|5[0-35-9]|6[567]|7[0-8]|8\d|9[0-35-9])\d{8}$/, message: "请输入合法手机号", trigger: "blur" }
        ],
        status: [
          {required: true, message: '请选择账号状态', trigger: 'change'}
        ],
        maxpaper: [
          {required: true, message: '请输入用户可发布问卷上限', trigger: 'blur'},
          { type: 'number', message: '用户可发布问卷上限必须为数字', trigger: 'blur'}
        ],
        securityQuestionContext: [
          {required: true, message: '请输入密保问题', trigger: 'blur'},
          { min: 4, max: 64, message: '长度在 4 到 64 个字符', trigger: 'blur' }
        ],
        securityQuestionAnswer: [
          {required: true, message: '请输入密保回答', trigger: 'blur'},
          { min: 4, max: 64, message: '长度在 4 到 64 个字符', trigger: 'blur' }
        ]
      },
      formLabelWidth: '120px',

    }
  },
  methods: {
    showAllUser(){
      console.log(this.loginerInfo.username)
      queryUserList(this.loginerInfo.username).then((response)=>{
        this.tableData = response.data.data
        console.log(response.data)
        this.total = response.data.data.length
      })
    },
    queryUser(key){
      console.log(this.loginerInfo.username)
      queryUserByKey(this.loginerInfo.username,key).then((response)=>{
        console.log(key)
        console.log(response.data)
        this.tableData = response.data.data
        this.total = response.data.data.length
      })
    },
    handleAdd () {
      this.clearForm()
      this.dialogTitle = '创建用户'
      this.userForm.status = 1
      this.dialogFormVisible = true
    },
    handleEdit (row) {
      this.clearForm()
      this.dialogTitle = '修改用户信息'
      for(let key in row){
        this.userForm[key] = row[key]
      }
      this.userForm.status = parseInt(row.status)
      this.dialogFormVisible = true
    },
    handleDelete (row) {
      this.$msgbox.confirm('确认删除此用户吗？', '删除警告', {type: 'warning', confirmButtonText: '确认删除'}).then(() => {
        removeUserByName(row.username).then((response) => {
          console.log(response.data)
          if (response.data.code == '200') {
            this.$message.success(response.data.message)
            this.showAllUser()
          } else {
            this.$message.error(response.data.message)
          }
        })
      }).catch(() => {})
    },
    handleClose () {
      this.clearForm()
      this.dialogFormVisible = false
    },
    handleConfirm(){
      this.$refs['userForm'].validate((valid) => {
        if(valid){
          let{
            id, username, password,telnumber, tenement,status, maxpaper, curpaper,securityQuestionContext,
            securityQuestionAnswer
          } = this.userForm
          if(this.dialogTitle == '创建用户'){
            let submitData = {
              username, password,telnumber, maxpaper,securityQuestionContext, securityQuestionAnswer,tenement
            }
            submitData.tenement = this.loginerInfo.username
            createUser(submitData).then((response)=>{
              console.log(response.data)
              if(response.data.code == '200'){
                this.$message.success(response.data.message)
                this.showAllUser()
                this.dialogFormVisible = false
              }else{
                this.$message.error(response.data.message)
              }
            })
            // console.log(submitData)
          }else if(this.dialogTitle == '修改用户信息'){
            let submitData = {
              id, username, telnumber, status, maxpaper,securityQuestionContext,
              securityQuestionAnswer
            }
            modifyUserInfo(submitData).then((response)=>{
              if(response.data.code == '200'){
                this.$message.success(response.data.message)
                this.showAllUser()
                this.dialogFormVisible = false
              }else{
                this.$message.error(response.data.message)
              }
            })
          }
        }
      })
    },
    handleCurrentChange: function (currentPage) {
      this.currentPage = currentPage
    },
    handleSizeChange (pageSize) {
      this.pageSize = pageSize
    },
    formatStatus (type) {
      const map = {
        0: '正常',
        1: '冻结'
      }
      return map[type]
    },
    getTagType(type){
      const map = {
        0 : 'success',
        1 : 'danger'
      }
      return map[type]
    },
    clearForm(){
      for(let key in this.userForm){
        this.userForm[key] = ''
      }
    }
  },
  created() {
    this.loginerInfo = JSON.parse(window.sessionStorage.getItem("data"))
    this.userForm.tenement = this.loginerInfo.username
    this.showAllUser()
  }
}
</script>

<style scoped>
.form{
  background-color: white;
  padding: 20px;
  margin-bottom: 20px;
}
.table{
  background: white;
  padding: 20px;
}
.table.table-title{
  padding-bottom: 20px;
  border-bottom: 1px solid #f3f3f3;
}
.dw-table.dw-table-title h3{
  padding: 0px;
  margin: 0px;
}
.el-form-item{
  margin-bottom: 0px;
}
.dw-dialog-form-item{
  margin-top: 20px;
}
.pagination{
  padding-top: 20px;
  text-align: right;
}
</style>
